﻿#include "TcpIOer.h"

TcpIOer::TcpIOer() : QTcpSocket()
{
  disconnectTimer=new QTimer();
  connect(this,&TcpIOer::destroyed,disconnectTimer,&QTimer::deleteLater,Qt::QueuedConnection);
  qRegisterMetaType<qintptr>("qintptr");
  qRegisterMetaType<QTcpSocket::SocketState>("QTcpSocket::SocketState");
  qRegisterMetaType<QTcpSocket::OpenMode>("QTcpSocket::OpenMode");
  qRegisterMetaType<TcpIOer::PrivateSignalClass>("TcpIOer::PrivateSignalClass");
  connect(this,&TcpIOer::readyRead,this,&TcpIOer::slot_readData,Qt::QueuedConnection);
  connect(this,&TcpIOer::signal_sendData,this,&TcpIOer::slot_sendData,Qt::QueuedConnection);
  void (QTcpSocket::*temp)(QAbstractSocket::SocketError) = &QTcpSocket::error;
  connect(this, temp, [this]() { logSaver->saveLog("tcpIOer,tcp error occured"); });
  connect(this, &TcpIOer::disconnected, [this](){emit signal_lastWish();});
  connect(this, &TcpIOer::disconnected, [this]() { logSaver->saveLog("tcpIOer,tcp disconnected"); });
  connect(this, &TcpIOer::disconnected, this,&TcpIOer::deleteLater);
  connect(&tcpDataPreprocessor,&TcpDataPreprocessor::signal_decoded,this,&TcpIOer::slot_temp);
  connect(disconnectTimer, &QTimer::timeout, [this]() {logSaver->saveLog("tcpIOer,time out,disconnect");disconnectFromHost();});
  void (QTimer::*temp1)(int)=&QTimer::start;
  connect(this,&TcpIOer::signal_setCountDown,disconnectTimer,temp1,Qt::QueuedConnection);
}

TcpIOer::~TcpIOer()
{
}

void TcpIOer::sendData(QByteArray data)
{
  emit signal_sendData(*tcpDataPreprocessor.code(&data));
}

void TcpIOer::setCountDown(int msec)
{
  emit signal_setCountDown(msec);
}

void TcpIOer::slot_sendData(QByteArray data)
{
  write(data);
  flush();
}

void TcpIOer::slot_readData()
{
  tcpDataPreprocessor.decode(readAll());
}

void TcpIOer::slot_temp(QByteArray data)
{
  emit signal_dataReceived(this,data);
}
